package com.spider.admin.service.app;

import com.spider.admin.conf.ResultMessage;
import com.spider.admin.conf.validator.Constants;
import com.spider.admin.exception.SpiderException;
import com.spider.admin.http.entity.PageResult;
import com.spider.admin.service.async.AsyncService;
import com.spider.admin.store.primary.mapper.AccountMapper;
import com.spider.admin.store.primary.mapper.AppMapper;
import com.spider.admin.store.primary.mapper.CloudMapper;
import com.spider.admin.store.primary.model.AppInfo;
import com.spider.admin.store.primary.model.CloudInfo;
import com.spider.admin.utils.CommonUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AppServiceImpl implements AppService {

    @Resource
    private AppMapper appMapper;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private CloudMapper cloudMapper;

    @Resource
    private AsyncService asyncService;

    @Override
    public int saveApp(AppInfo appInfo) throws SpiderException {
        appInfo.setPid(CommonUtil.getUniqueKey()).setAppStatus(Constants.ACTIVE.getCode());

        long count = accountMapper.getActiveTenantCountById(appInfo.getTenantId());
        if (count <= 0) {
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "归属租户未激活或不存在");
        }

        CloudInfo cloudInfo = cloudMapper.getActiveCloudById(appInfo.getCloudId());
        if (cloudInfo == null) {
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "发布服务云未激活或不存在");
        }
        if (!appInfo.getTenantId().equals(cloudInfo.getTenantId())) {
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "服务云与归属租户不匹配");
        }
        int i = appMapper.saveApp(appInfo);
//        log.info("新增API应用：{}", appInfo.getAppName());
        asyncService.asyncRefashPermsCache();
        asyncService.asyncRefashServiceInfoCache();
        return i;
    }

    @Override
    public int updateApp(AppInfo appInfo, String pid) throws SpiderException {
        appInfo.setAppStatus(null);
        long count = appMapper.getAppRecordNumByNotId(pid, appInfo.getAppName(),null);
        if(count>0){
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "应用名称已被占用");
        }
        int i = appMapper.updateApp(appInfo, pid);
//        log.info("更新API应用：{}", pid);
        asyncService.asyncRefashPermsCache();
        asyncService.asyncRefashServiceInfoCache();
        return i;
    }

    @Override
    public int activeApp(String pid) throws SpiderException {
        AppInfo appInfo = new AppInfo();
        appInfo.setAppStatus(Constants.ACTIVE.getCode());
        int i = appMapper.updateApp(appInfo, pid);
//        log.info("激活API应用：{}", pid);
        asyncService.asyncRefashPermsCache();
        return i;
    }

    @Override
    public int archiveApp(String pid) throws SpiderException {
        AppInfo appInfo = new AppInfo();
        appInfo.setAppStatus(Constants.ARCHIVE.getCode());
        int i = appMapper.updateApp(appInfo, pid);
//        log.info("归档API应用：{}", pid);
        asyncService.asyncRefashPermsCache();
        return i;
    }

    @Override
    public AppInfo queryAppById(String pid) throws SpiderException {
        return appMapper.queryAppById(pid);
    }

    @Override
    public PageResult<AppInfo> queryAppByTenantId(String tenantId, Integer page, Integer pageSize, String appName, String cloudId, String appStatus) {
        page = page == null || page.intValue() <= 0 ? 1 : page;
        pageSize = pageSize == null ? 10 : pageSize;
        long totalCount = appMapper.getAppRecordNum(tenantId, appName, cloudId, appStatus);
        int totalPage = (int) Math.ceil((double) totalCount / (double) pageSize);
        page = page > totalPage ? totalPage : page;
        page = page <= 0 ? 1 : page;
        PageResult<AppInfo> result = new PageResult<>();
        result.setCurrentPage(page);
        result.setPageSize(pageSize);
        result.setTotal(totalCount);
        result.setTotalPage(totalPage);

        List<AppInfo> records = appMapper.queryAppByTenantId((page - 1) * pageSize, pageSize, tenantId, appName, cloudId, appStatus);
        result.setList(records);

        return result;
    }
}

